using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text;
using Localization;
using SinBiota.Model.Entities.CustomAttributes;


namespace SinBiota.Model.Entities
{
    [LocalizedName("Taxon", NameResourceType = typeof(Strings))]
    public class Taxon : BaseEntity
    {
        [Required(ErrorMessageResourceType = typeof(Messages), ErrorMessageResourceName = "FieldCannotBeEmpty")]
        [LocalizedName("Name", NameResourceType = typeof(Strings))]
        public virtual string Name { get; set; }

        [Required(ErrorMessageResourceType = typeof(Messages), ErrorMessageResourceName = "FieldCannotBeEmpty")]
        [LocalizedName("TaxonomicRank", NameResourceType = typeof(Strings))]
        public virtual string Rank { get; set; }

        [LocalizedName("Parent", NameResourceType = typeof(Strings))]
        public virtual Taxon Parent { get; set; }

        [LocalizedName("Publication", NameResourceType = typeof(Strings))]
        public virtual TaxonReference TaxonReference { get; set; }

        public virtual User IncludedByUser { get; set; }

        public virtual string ScientificName()
        {
            if (Rank.Contains(COLRank.Genus)) return string.Format("{0} sp.", Name);
            
            if (Rank.Contains(COLRank.Species))
            {
                var temp = this;
                var sb = new List<string>();
                while (true)
                {
                    sb.Add(temp.Name);
                    if (temp.Rank.Contains(COLRank.Genus)) break;
                    temp = temp.Parent;
                    if (temp == null) break;
                }
                sb.Reverse();
                return String.Join(" ", sb);
            }

            return Name;
        }

    }

    public static class COLRank
    {
        public const string Phylum = "phylum";
        public const string Order = "order";
        public const string SubOrder = "suborder";
        public const string Family = "family";
        public const string SuperFamily = "superfamily";
        public const string Genus = "genus";
        public const string Species = "species";
        public const string SubSpecies = "subspecies";
    }
}
